package com.tzy.rpc.serializer;/**
 * @description:
 * @Author HP
 * @create 2022/3/15 20:02
 */

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.tzy.rpc.enumeration.SerializerCode;
import com.tzy.rpc.exception.SerializeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author HP
 * @create 2022-03-15 20:02
 * @desc
 **/
public class HessianSerializer implements CommonSerializer{

    private static final Logger logger = LoggerFactory.getLogger(HessianSerializer.class);

    @Override
    public byte[] serialize(Object obj) {
        HessianOutput hessianOutput=null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            hessianOutput = new HessianOutput(byteArrayOutputStream);
            hessianOutput.writeObject(obj);
            return byteArrayOutputStream.toByteArray();
        }catch (Exception e){
            logger.error("序列化时发生错误：", e);
            throw new SerializeException("序列化时有错误发生：");
        }finally {
            if (hessianOutput!=null){
                try {
                    hessianOutput.close();
                } catch (IOException e) {
                    logger.error("关闭流时有错误发生：", e);
                }
            }
        }
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        HessianInput hessianInput=null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            hessianInput=new HessianInput(byteArrayInputStream);
            Object o = hessianInput.readObject();
            return o;
        }catch (Exception e){
            logger.error("序列化时发生错误：", e);
            throw new SerializeException("序列化时有错误发生：");
        }finally {
            if (hessianInput!=null){
                try {
                    hessianInput.close();
                } catch (Exception e) {
                    logger.error("关闭流时有错误发生：", e);
                }
            }
        }
    }

    @Override
    public int getCode() {
        return SerializerCode.valueOf("HESSIAN").getCode();
    }
}
